package personal.wang.juc.juc;


import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @className: PrintRotation
 * @Description:
 * @Author: wangyifei
 * @Date: 2025/3/21 17:17
 */
public class PrintRotation {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger integer = new AtomicInteger(1);
        Thread thread1 = null ;
        Thread thread2 = null ;
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        thread1 = new Thread(()->{
            int i = 0 ;
            while((i = integer.get()) < 11){
                lock.lock();
                try{
                    if(i%2 == 0){
                        System.out.println(i);
                        integer.incrementAndGet();
                        condition.signalAll();
                    }else{
                        condition.await();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        });
        thread1.start();
        thread2 = new Thread(()->{
            int i = 0 ;
            while((i = integer.get()) < 10){
                lock.lock();
                try{
                    if(i%2 != 0){
                        System.out.println(i);
                        integer.incrementAndGet();
                        condition.signalAll();
                    }else{
                            condition.await();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                  lock.unlock();
                }
            }
        });
        thread2.start();
        thread1.join();
        thread2.join();
    }
}
